package com.kpy.consumerribbonhystrix.controller;

import com.kpy.consumerribbonhystrix.model.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @auther: kpy
 * @version: 1.0
 * @Package: com.kpy.consumerribbonhystrix.controller
 * @data: 2022-3-1 18:46
 * @discription:
 **/

@RestController
public class ConsumerController {

    private final static Logger LOGGER = LoggerFactory.getLogger(ConsumerController.class);

    private RestTemplate restTemplate;

    private LoadBalancerClient loadBalancerClient;

    public ConsumerController(RestTemplate restTemplate, LoadBalancerClient loadBalancerClient) {
        this.restTemplate = restTemplate;
        this.loadBalancerClient = loadBalancerClient;
    }

    //熔断
    @HystrixCommand(fallbackMethod = "findByIdFallback")

    @GetMapping("/user/{id}")
    public User findById(@PathVariable long id){
        System.out.println("id="+id);
        return this.restTemplate.getForObject("http://provider/"+id, User.class);
    }

    @GetMapping("/log-instance")
    public void logConsumerInstance(){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("provider");
        ConsumerController.LOGGER.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
    }

    //熔断后处理措施
    public User findByIdFallback(long id){
        User user = new User();
        user.setId(-1);
        user.setName("默认用户");
        return user;
    }
}
